package com.smooware.icms.app;

import android.os.Bundle;
import android.support.v4.app.ActionBar;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.smooware.icms.InControllApp;
import com.smooware.icms.fragment.navigation.AbstractFragmentNavigator;

/**
 * Base activity that performes verification if security module needs to be
 * started.
 * 
 * @author Orest Vovchak
 */
public abstract class ICMSLauncherActivity extends FragmentActivity {

	private static final String TAG = ICMSLauncherActivity.class
			.getSimpleName();

	protected AbstractFragmentNavigator abstractFragmentNavigator;

	protected InControllApp application;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		initActionBar();

		super.onCreate(savedInstanceState);

		application = (InControllApp) getApplicationContext();

		abstractFragmentNavigator = initFragmentNavigator();

		performAuthorizationCheck();
	}

	@Override
	protected void onStart() {
		super.onStart();

		if (!abstractFragmentNavigator.isLockedByAuthorization()) {
			performAuthorizationCheck();
		}
	}

	/**
	 * Check if user's access is trusted. If not takes him to authorization
	 * fragment where his account and credentials are checked.
	 */
	private void performAuthorizationCheck() {
		if (!application.getICMSSecurityManager().isTrustedAccess()) {
			Log.d(TAG, "security module needs to be started");

			abstractFragmentNavigator.goToAuthorizationFragment();
		}
	}

	/**
	 * Initiates instance of {@link AbstractFragmentNavigator} which is used
	 * later for navigation between fragments
	 * 
	 * @return instance of {@link AbstractFragmentNavigator} which is used later
	 *         for navigation between fragments.
	 */
	protected abstract AbstractFragmentNavigator initFragmentNavigator();

	/**
	 * Initiates {@link ActionBar} if it will be needed, because it can only be
	 * done during OnCreate() method.
	 */
	protected abstract void initActionBar();

	/**
	 * Hides {@link ActionBar} when it's not needed.
	 */
	protected void hideActionBar() {
		getSupportActionBar().hide();
	}

	/**
	 * Shows {@link ActionBar} when it's needed.
	 */
	protected void showActionBar() {
		getSupportActionBar().show();
	}
}
